package com.lqzs.businessmanager.ui.main.activity

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.lqzs.businessmanager.BusinessManagerApplication
import com.lqzs.businessmanager.Config
import com.lqzs.businessmanager.R
import com.lqzs.businessmanager.adapter.BusinessAdapter
import com.lqzs.businessmanager.base.BaseActivity
import com.lqzs.businessmanager.bean.event.HomeClickEvent
import com.lqzs.businessmanager.bean.event.ServiceEvent
import com.lqzs.businessmanager.bean.response.LoginShopResponse
import com.lqzs.businessmanager.dao.AccessDao
import com.lqzs.businessmanager.dao.AccessDataBase
import com.lqzs.businessmanager.databinding.ActivityMainBinding
import com.lqzs.businessmanager.service.AccessibilitySampleService.Companion.TAG
import com.lqzs.businessmanager.ui.main.vm.MainViewModel
import com.lqzs.businessmanager.utils.PreferencesUtil
import com.lqzs.businessmanager.utils.StringUtils
import com.lqzs.businessmanager.utils.isOpenAccessibility
import com.lqzs.businessmanager.utils.showCustomToast
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


//茶乙己 15557168087
class MainActivity : BaseActivity<ActivityMainBinding,MainViewModel>(R.layout.activity_main) {

    lateinit var accessDao:AccessDao
    lateinit var mAdapter:BusinessAdapter
    private val mList: MutableList<LoginShopResponse> = mutableListOf()
    private var isAutoMode = true;

    override fun initView() {
        PreferencesUtil.putInt(this,Config.ELE_YES_REPLAY,1)
        //实例化数据库表
        accessDao = AccessDataBase.getDataBase().accessDao()
       // initPermission()
        val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.rvList.layoutManager = linearLayoutManager
        mAdapter = BusinessAdapter(mList, this)
        binding.rvList.adapter = mAdapter
        getBottomNavigationBarHeight()
    }

    override fun onStart() {
        super.onStart()

        if (isOpenAccessibility(this)){
            binding.tvPermission.visibility = View.GONE
            binding.btOpenPermission.visibility = View.GONE
            binding.tvLogin.visibility = View.VISIBLE
            binding.llReplayMode.visibility = View.GONE
        }else{
            binding.tvPermission.visibility = View.VISIBLE
            binding.btOpenPermission.visibility = View.VISIBLE
            binding.tvLogin.visibility = View.GONE
            binding.llReplayMode.visibility = View.GONE
        }
    }

    override fun onResume() {
        super.onResume()
        //如果登录按钮不可见，说明是已经登录过的。重新登录一遍拉去数据.
        //条件的判断是判断的登录按钮或者包裹着登录按钮的layout（这是代码设计的问题，之后优化）
        if((super.binding.tvLogin.visibility==View.GONE||super.binding.loginLayout.visibility==View.GONE)&&super.binding.btOpenPermission.visibility==View.GONE){
            mViewModel.bindingShop(binding.edShopPhone.text.toString().trim())
        }
    }
    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        mAdapter.setOnItemAdapterClickListener(object :BusinessAdapter.OnItemAdapterClickListener{
            override fun onClick(position: Int, mData: LoginShopResponse) {
                BusinessManagerApplication.setVendorInfo(mData)
                if(isAutoMode) {
                    val intent = Intent(BusinessManagerApplication.getContext(), DetailCommentActivity::class.java)
                    intent.putExtra("vendorInfo", mData)
                    startActivity(intent)
                    return
                }
                open(mData)
            }

        })

        binding.tvLogin.setOnClickListener{
            if (!isOpenAccessibility(this)){
                showCustomToast(this,"请先打开无障碍服务权限")
                return@setOnClickListener
            }
            val shopPhone = binding.edShopPhone.text.toString().trim()
            if (TextUtils.isEmpty(shopPhone)){
                showCustomToast(this,"商家手机号不能为空")
                return@setOnClickListener
            }
            if (!StringUtils.isValidPhoneNumber(shopPhone)) {
                showCustomToast(this,"请输入正确的商家手机号")
                return@setOnClickListener
            }
            mViewModel.bindingShop(shopPhone)
        }

        mViewModel.shopId.observe(this) {newData->
            mList.clear()
            mList.addAll(newData)
            mAdapter.notifyDataSetChanged()
            binding.loginLayout.visibility=View.GONE
            binding.rvList.visibility=View.VISIBLE
            binding.mainLogout.visibility=View.VISIBLE
            //下边目前看来是数据库操作
            if(newData.isNotEmpty()) {
                for (loginShopResponse in newData) {
                    mViewModel.getUnReplyReview(loginShopResponse.branch_id,
                        loginShopResponse.vendor_id, loginShopResponse.vendor_name)
                }
            }
//             mViewModel.getUnReplyReviewRecycle()
        }

        binding.btOpenPermission.setOnClickListener {



            if (!isOpenAccessibility(this)){
                val intent = Intent(this, GuideActivity::class.java)
                startActivity(intent)


//                try {
//                    startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
//                } catch (e:Exception) {
//                    e.printStackTrace()
//                }
            }else{
                openApp(Config.PACKAGE_NAME_MEITUAN_TAKEAWAY_BUSINESS,Config.MEITUAN_WAIMAI_BUSINESS_MAIN,1)
            }
        }
        binding.cbReplayMode.setOnCheckedChangeListener { buttonView, isChecked ->
            isAutoMode = isChecked
        }
        binding.mainLogout.setOnClickListener{
            mList.clear()
            mAdapter.notifyDataSetChanged()
            binding.loginLayout.visibility=View.VISIBLE
            binding.mainLogout.visibility=View.GONE
            binding.rvList.visibility=View.GONE
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun serviceEvent(event:ServiceEvent){
        Log.e(TAG,"服务已连接")
        event.vendorInfo?.let {
            open(event.vendorInfo)
            return
        }

        if (!isOpenAccessibility(this)){
            showCustomToast(this,"请先打开无障碍服务权限")
            return
        }
        val shopPhone = binding.edShopPhone.text.toString().trim()
        if (TextUtils.isEmpty(shopPhone)){
            showCustomToast(this,"商家手机号不能为空")
            return
        }
        if (!StringUtils.isValidPhoneNumber(shopPhone)) {
            showCustomToast(this,"请输入正确的商家手机号")
            return
        }
    }

    private fun openApp(packageName : String, path: String?, type:Int){
        val intent = packageManager?.getLaunchIntentForPackage(packageName)
        if (intent == null) {
            Log.e("Accessibility", "intent = $intent")
        } else {
            path?.let {
                val componentName = ComponentName(packageName, it)
                intent.setComponent(componentName)
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
            val homeClickEvent = HomeClickEvent(type,binding.root.measuredWidth,binding.root.measuredHeight)
            homeClickEvent.measureWidth = binding.root.measuredWidth
            homeClickEvent.measureHeight = binding.root.measuredHeight
            homeClickEvent.type = type
            EventBus.getDefault().post(homeClickEvent)
        }
    }

    private fun initPermission() {
//动态申请权限
        if (!AndPermission.hasPermissions(this,Permission.Group.STORAGE)){
            AndPermission.with(this@MainActivity)
                .runtime()
                .permission(Permission.Group.STORAGE) //权限组
                .onGranted {
                    showCustomToast(this,"获取权限成功")
                    if (!isOpenAccessibility(this)){
                        try {
                            startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
                        } catch (e:Exception) {
                            e.printStackTrace()
                        }
                    }
                } //权限调用成功后的回调
                .onDenied {
                    showCustomToast(this,"获取权限失败")
                    if (!isOpenAccessibility(this)){
                        try {
                            startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
                        } catch (e:Exception) {
                            e.printStackTrace()
                        }
                    }
                } //权限调用失败后的回调
                .start()
        }else{
            if (!isOpenAccessibility(this)){
                try {
                    startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
                } catch (e:Exception) {
                    e.printStackTrace()
                }
            }
        }

    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // 获取触摸事件的动作类型
        val action = event.actionMasked
        when (action) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP -> {
                // 获取触摸点的个数
                val pointerCount = event.pointerCount
                var i = 0
                while (i < pointerCount) {
                    // 获取每个触摸点的索引
                    val pointerIndex = event.getPointerId(i)
                    // 获取触摸点的 X 坐标
                    val x = event.getX(i)
                    // 获取触摸点的 Y 坐标
                    val y = event.getY(i)

                    // 在这里，你可以使用坐标点 x 和 y
                    // 例如，将它们打印出来
                    Log.d("Gesture Coordinates", "Pointer $pointerIndex - X: $x, Y: $y")
                    i++
                }
            }
        }
        return true // 返回 true 表示事件已消费
    }

    override fun isRegisterEventBus() = true
    override fun createViewBinding(view: LayoutInflater) = ActivityMainBinding.inflate(view)

    override fun createViewModel() = MainViewModel(this)


    fun open(vendorInfo: LoginShopResponse?) {
        vendorInfo?.let {
            when (vendorInfo.platform_name) {
                "美团外卖"->{
                    openApp(Config.PACKAGE_NAME_MEITUAN_TAKEAWAY_BUSINESS,Config.MEITUAN_WAIMAI_BUSINESS_MAIN,1)
                }
                "饿了么"->{
                    openApp(Config.PACKAGE_NAME_NAPOS,null,2)
                    PreferencesUtil.putInt(this@MainActivity,Config.ELE_YES_REPLAY,0)
                    PreferencesUtil.putInt(this@MainActivity,Config.ELE_NO_REPLAY,0)
                }
                "美团到店"->{
                    PreferencesUtil.remove(this@MainActivity,Config.Merchant_MT)
                    PreferencesUtil.remove(this@MainActivity,Config.Merchant_DaZhongDianPing)
                    PreferencesUtil.remove(this@MainActivity,Config.Merchant_DZDP_NO_REPLAY)
                    PreferencesUtil.remove(this@MainActivity,Config.Merchant_DZDP_ZD)
                    openApp(Config.PACKAGE_NAME_MERCHANT,null,3)
                }
            }
        }

    }

    fun getBottomNavigationBarHeight() {
        val rootView = findViewById<View>(android.R.id.content)
        // 获取底部导航栏的高度
        rootView.setOnApplyWindowInsetsListener { view, insets ->
            val navigationBarHeight = insets.systemWindowInsetBottom
            BusinessManagerApplication.setBottomNavigationBarHeight(navigationBarHeight)
            insets.systemWindowInsetBottom
            view.onApplyWindowInsets(insets)
        }
    }
}